package multi_thread.master.tools;

import multi_thread.advanced.blocking_queue.SynchronousQueueExample;

import java.util.concurrent.Exchanger;
import java.util.concurrent.TimeUnit;

/**
 * @author Cheng Jun
 * Description: 看 Exchanger.java 的类注释
 * An Exchanger may be viewed as a bidirectional form of a SynchronousQueue.
 * Exchangers may be useful in applications such as genetic algorithms and pipeline designs.
 * Exchanger 可以被看做一个 双向形式的 SynchronousQueue，其实就是两个线程之间彼此交换数据。
 * Exchanger 主要被用于遗传算法和管道（数据双向传输）设计
 * @version 1.0
 * @date 2022/5/18 9:55
 * @see SynchronousQueueExample
 */
public class ExchangerExample {

    public static void main(String[] args) {
        Exchanger<String> nameExchanger = new Exchanger<>();
        new Thread(() -> {
            String name = "cauchy";
            try {
                System.out.println(Thread.currentThread().getName() + "交换前 name: " + name);
                name = nameExchanger.exchange(name);
                System.out.println(Thread.currentThread().getName() + "交换后 name: " + name);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        new Thread(() -> {
            String name = "cauchy6317";
            try {
                System.out.println(Thread.currentThread().getName() + "交换前 name: " + name);
                TimeUnit.SECONDS.sleep(2);
                // 必须等到两个线程都到达 exchange 方法。也有带时间的 exchange 方法
                name = nameExchanger.exchange(name);
                System.out.println(Thread.currentThread().getName() + "交换后 name: " + name);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
}
